package xyz.masaikk;

public class BlackboardN {

    private static int numOfQueens;
    private static int resultCount;
    private static int line;
    private static int row;
    private static int[] lactionq;

    public BlackboardN(int numOfQueen) {
        //初始化
        BlackboardN.numOfQueens = numOfQueen;
        lactionq = new int[numOfQueens];
        row = line = resultCount = 0;
        //线程组
        Thread[] threadQueen = new Thread[numOfQueens];

        int temp = 0;

        //默认皇后都在第一行
        for (int i = 0; i < numOfQueens; i++)
            lactionq[i] = 0;



        while(line >= 0) {
            //线程组开始按顺序运行
            threadQueen[temp] = new Thread(new SearchQueen());
            //开始
            threadQueen[temp].start();

            try {
                threadQueen[temp].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if(temp + 1 == numOfQueens) temp = -1;//当
            temp++;
        }
    }

    public int getResultCount() { // ���ؽ����Ŀ
        return resultCount;
    }



    static class SearchQueen implements Runnable {

        public SearchQueen() {
        }
        //从当前queen所在位置向后检查是否可以落位
        private boolean isValid(int line, int row) {
            for (int i = 1; i <= line; i++)
                if (lactionq[line - i] == row//在同一列
                        || lactionq[line - i] == row - i//在主对角线上
                        || lactionq[line - i] == row + i)//在副对角线上
                    return false;
            return true;
        }

        @Override
        public void run() {
            //第line行皇后的列数
            row = lactionq[line];
            while (row < numOfQueens) {
                if (isValid(line, row)) {
                    lactionq[line] = row;
                    break;
                }
                row++;
            }

            if (row < numOfQueens) {
                //如果完成一个numOfQueens的循环，则说明得到一个成功的解
                if (line + 1 == numOfQueens) {
                    resultCount++;//结果+1
                    lactionq[line] += 1;
                } else
                    lactionq[++line] = 0;
            } else {
                line--;
                if (line >= 0)
                    lactionq[line] += 1;
            }
        }


    }
}
